NetManager = BaseClass:Extend()
local CSNetManager = CS.SocketManager
local ICSNetManager = CSNetManager.Instance

function NetManager:New()
    local o = NetManager.super.New(self)
    o.proto_callback = {}
    o:Init()
    return o
end

function NetManager:Init()
    self:BindCallback()
end

function NetManager:GetInstance()
    if self.instance == nil then
        self.instance = self:New()
    end
    return self.instance
end

function NetManager:BindCallback()
    CS.SocketManager.Instance:BindCallBack(
        function()
            print("LUA: CONNECT_SUCCESS -----  连接成功")
            NetManager.connect = true
            EventManager:Fire(Events.CONNECT_SUCCESS)
        end,
        function()
            self:HandlerReceiveData()
        end,
        function()
            NetManager.connect = false
            print("LUA: DISCONNECT -----  断开服务器连接")
        end
    )
end

--连接服务器
function NetManager:Connect(ip, port)
    CSNetManager.Instance:Connect(ip or "43.138.141.127", port or "8885")
end

--收到协议
function NetManager:HandlerReceiveData()
    local cacheReceive = ICSNetManager.cacheReceive
    local pts = Split(cacheReceive, "<pt>")
    if #pts > 0 then
        for i, str in ipairs(pts) do
            if str ~= "" then
                print("Rec ---->>>>>  ", str)
                local msg = StrToTable(str)
                if not msg then
                    error("msg格式错误！！！！")
                    return
                end
                if msg.protoID then
                    msg.protoID = tonumber(msg.protoID) or 0
                end
                if not msg.protoID then
                    error("协议ID解析失效")
                    return
                end
                if not self.proto_callback[msg.protoID] then
                    error("协议ID未绑定 " .. msg.protoID)
                    return
                end
                if msg.protoID and self.proto_callback[msg.protoID] then
                    print("LUA: RECEIVE MSG -----  ", msg.protoID, str)
                    local pvo = self.proto_callback[msg.protoID]
                    if not pvo or not pvo.func then
                        error("协议ID未绑定 " .. msg.protoID)
                    else
                        pvo.func(pvo.that, msg)
                    end
                end
            end
        end
    end
end

--发送协议
function NetManager:Send(id, args)
    args.protoID = args.protoID or id
    local str = TableToStr(args)
    print("LUA: SEND MSG -----  ", id, str)
    CSNetManager.Instance:AddDataSend(str)
end

--发送协议
function NetManager:BindProto(id, func, that)
    if not self.proto_callback then self.proto_callback = {} end
    self.proto_callback[id] = { that = that, func = func }
end
